package org.jeecg.modules.hotel.belongToSkd.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.basic.entry.entity.LwgyInoutRecord;
import org.jeecg.modules.basic.entry.service.ILwgyInoutRecordService;
import org.jeecg.modules.hotel.belongToSkd.entity.HKReceiveData;
import org.jeecg.modules.hotel.belongToSkd.service.ILwgyHotelEventRcvService;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.lang.StringUtils;


import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @author:MJ-BaBa
 * @date: 2022.12.27
 */

@Api(tags = "海康-订阅事件报文返回数据")
@RestController
@RequestMapping("/belongToSkd")
@Slf4j
public class LwgyHotelEventRcvController {

    @Autowired
    private ILwgyHotelEventRcvService lwgyHotelEventRcvService;
    @Autowired
    private ILwgyInoutRecordService iLwgyInoutRecordService;
    /**
     * 山科大宿舍人走断电，人来有电
     * 海康-订阅事件报文返回数据
     */
    @AutoLog(value = "海康-订阅事件报文返回数据")
    @ApiOperation(value="海康-订阅事件报文返回数据",notes = "海康-订阅事件报文返回数据")
    @PostMapping(value = "/receiveData")
    @ResponseBody
    public Result<?> receiveData(@RequestBody Map<String, Object> msg ) {


        try {
            log.info("一条山科大进出宿舍推送数据----------:" + msg);
            if (msg == null || msg.isEmpty()) {
                return Result.error(1,"请求参数不能为空");
            }

            JSONObject json = JSONObject.fromObject(msg);
            JSONObject data = json.getJSONObject("params");
            JSONObject  dormData = data.getJSONObject("dormEvent");
            JSONArray eventData = data.getJSONArray("events");
            JSONObject  alarmData = dormData.getJSONObject("alarmInfo");
            JSONObject  studentData = dormData.getJSONObject("student");

            String sendTime = data.getString("sendTime");// 事件从接收者（如设备接入框架）发出的时间
            String entryType = alarmData.getString("entryType");// 进出类型 in:进，out:出
            int entryMode = alarmData.getInt("entryMode");// 进出方式 0:刷脸，1:刷卡

            JSONObject firstEvent = eventData.getJSONObject(0);
            String eventId = firstEvent.getString("eventId");// 事件id
            String eventType = firstEvent.getString("eventType");// 订阅事件码

            String studentId = studentData.getString("studentId");// 学生id
            String name = studentData.getString("name");// 姓名
            String studentCode = studentData.getString("studentCode");// 学工号
            int sex = studentData.getInt("sex");// 性别 0-未知；1-男性；2-女性
            int personType = studentData.getInt("personType");// 人员类型

            int inDormNum = dormData.getInt("inDormNum");// 在寝人数
            String dormCode = dormData.getString("dormCode");// 学生所在宿舍路径
            int dormStuNum = dormData.getInt("dormStuNum");// 宿舍已经入住人数
            //时间戳转成时间
            DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTime();
            DateTime dateTime = dateTimeFormatter.parseDateTime(sendTime);
            Date date = dateTime.toDate();

            LwgyInoutRecord lwgyInoutRecor = new LwgyInoutRecord();
            String id = UUIDGenerator.generate();
            lwgyInoutRecor.setId(id);
            lwgyInoutRecor.setGuestId(String.valueOf(eventId));
            lwgyInoutRecor.setUserId(studentCode);
            lwgyInoutRecor.setUserName(String.valueOf(name));
            lwgyInoutRecor.setDirection(String.valueOf(entryType));
            lwgyInoutRecor.setType(String.valueOf(personType));
            lwgyInoutRecor.setRecordDate(date);
            System.out.println("lwgyInoutRecor ==========" + lwgyInoutRecor);
            iLwgyInoutRecordService.save(lwgyInoutRecor);

            if(personType == 1 || personType == 2){// 1-代表教职工 2-代表学生
                if (StringUtils.isBlank(dormCode) || dormCode.lastIndexOf("/") < 0) {
                    return Result.error(1, "宿舍编码不合法");
                }
                HKReceiveData receiveData = new HKReceiveData();
                receiveData.setSendTime(date);
                receiveData.setEntryType(entryType);
                receiveData.setEntryMode(entryMode);
                receiveData.setEventId(eventId);
                receiveData.setEventType(eventType);
                receiveData.setStudentId(studentId);
                receiveData.setName(name);
                receiveData.setStudentCode(studentCode);
                receiveData.setSex(sex);
                receiveData.setPersonType(personType);
                receiveData.setInDormNum(inDormNum);
                receiveData.setDormCode(dormCode);
                receiveData.setDormStuNum(dormStuNum);
                System.out.println("receiveData ========== " + receiveData);
                lwgyHotelEventRcvService.writeInApartment(receiveData);// 保存到表apartment,领导用后台程序开关电
            }
        } catch (JSONException e){
            return Result.error(1,"数据格式不正确");
        }catch (Exception e){
            log.error("消息处理异常：", e);
            return Result.error(1,"消息处理异常:" + e.getMessage());
        }
        return Result.OK("success");
    }
}
